﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ArbolandiaBL
{
    internal class PreferenceProvider : PreferenceBase
    {
        private ImageProvider _imgprov;
        internal PreferenceProvider()
            : base() { _imgprov = new ImageProvider(); }

        internal List<Product_Preference> GetPreferences()
        {
            var query = _db.Product_Preference.Select(w => w);
            return query.Count() > 0 ? query.ToList() : new List<Product_Preference>();
        }
        internal List<object> GetPicturePreference(Int32 id)
        {
            var res = new List<object>();

            var query = from s in _db.spGetPicturePreference(id)
                        select new
                        {
                            GuidId = s.GuidId,
                            Name = s.Name,
                            url = s.url
                        };
            foreach (var item in query)
            {
                res.Add(new
                {
                    GuidId = item.GuidId,
                    Name = item.Name,
                    url = item.url
                });
            }
            return res;
        }
        internal void InsertPicturePreference(Int32 id, Guid guid, Picture picture)
        {
            //Guardamos la imagen y la damos de alta en arb_picture
            picture.GuidId = guid;
            _imgprov.InsertUpdateImage(picture);

            //actualizamos el guid en la tabla de subcategorias
            UpdatePictureGuidPreference(id, guid);
        }
        internal void UpdatePictureGuidPreference(Int32 id, Guid guid)
        {

            var query = _db.Product_Preference.Where(w => w.Id == id);
            if (query.Count() > 0)
            {
                query.First().PictureGuidId = guid;
                _db.SubmitChanges();
            }
        }
        internal void DeletePicturePreference(Int32 id)
        {
            var query = from s in _db.Product_Preference
                        join p in _db.Picture on s.PictureGuidId equals p.GuidId
                        where s.Id == id
                        select p;
            if (query.Count() > 0)
            {
                _db.Picture.DeleteOnSubmit(query.First());
                _db.SubmitChanges();
            }

        }
        internal Product_Preference GetPreferenceId(Int32 id)
        {
            var query = _db.Product_Preference.Where(w => w.Id == id);
            return query.Count() > 0 ? query.FirstOrDefault<Product_Preference>() : new Product_Preference();

        }

    }
}
